package com.jiawa.train.member.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.train.common.req.MemberTicketReq;
import com.jiawa.train.common.resp.PageResult;
import com.jiawa.train.common.util.SnowUtil;
import com.jiawa.train.member.domain.Ticket;
import com.jiawa.train.member.domain.TicketExample;
import com.jiawa.train.member.mapper.TicketMapper;
import com.jiawa.train.member.req.TicketQueryReq;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TicketService {
    //reource是使用名称注入的方式而autowired是使用类型注入的方式
    @Resource
    private TicketMapper ticketMapper;

    //新增或者更新用户信息，通过判断是否有id决定进行新增操作还是更新操作
    public void save(MemberTicketReq req) throws  Exception{
        DateTime now = DateTime.now();
        Ticket ticket = BeanUtil.copyProperties(req, Ticket.class);
        ticket.setId(SnowUtil.getSnowflakeNextId());
        ticket.setCreateTime(now);
        ticket.setUpdateTime(now);
        ticketMapper.insert(ticket);
//         模拟被调用方出现异常
//       if (1 == 1) {
//          throw new Exception("测试异常11");
//          }
    }

    //如果用户id存在则进行根据id进行查询乘客的信息，如果是用户id不存在则进行查询所有,全部都按分页进行处理
    public PageResult queryTicketList(TicketQueryReq  req) {
        //创建ticketExample对象
        TicketExample ticketExample = new TicketExample();
        ticketExample.setOrderByClause("id desc");
        //设置查询条件
        TicketExample.Criteria criteria = ticketExample.createCriteria();

        if(ObjectUtil.isNotNull(req.getMemberId())){
            criteria.andMemberIdEqualTo(req.getMemberId());
        }
        // 先设置分页的参数
        PageHelper.startPage(req.getPage(),req.getPageSize());
        //进行查询数据库
        List<Ticket> ticketList = ticketMapper.selectByExample(ticketExample);
        //返回查询结果,转为分页的形式,
        PageInfo<Ticket> pageInfo = new PageInfo<>(ticketList);
        //获取数据进行封装
        PageResult pageResult = new PageResult(pageInfo.getTotal(), pageInfo.getList());
        //返回查询结果
        return pageResult;
    }

    public void delete(Long id) {
        ticketMapper.deleteByPrimaryKey(id);
    }
}